package com.demo.pickacontact;

import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

/**
 * Demo for startActivityForResult() using the contacts api and application,
 * query de contact provider and, demo for onSaveInstanceState() and
 * onRestoreInstanceState() when configuration changes and/or application is
 * destroyed
 * 
 * @author alquad
 * 
 */
public class MainActivity extends Activity {

	private TextView txtvContact;
	private Button btnPickAContact;
	private static final int PICK_CONTACT_REQUEST = 123;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		this.txtvContact = (TextView) findViewById(R.id.txtvConctact);
		this.btnPickAContact = (Button) findViewById(R.id.btnPickContact);

		this.btnPickAContact.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				pickAContact();
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == PICK_CONTACT_REQUEST) {
			if (resultCode == RESULT_OK) {
				Uri uriResult = data.getData();

				Log.i("PickAContact", "data = " + uriResult);

				ContactDataAsyncTask asyncData = new ContactDataAsyncTask();
				try {
					// returns the result
					txtvContact.setText(asyncData.execute(uriResult).get());
				} catch (Exception e) {
				}
			} else
				Log.i("PickAContact", "error");
		}
	}

	private void pickAContact() {
		Uri uri = Uri.parse("content://contacts");
		Intent pickContactIntent = new Intent(Intent.ACTION_PICK, uri);
		// Show user only contacts w/ phone numbers
		pickContactIntent.setType(Phone.CONTENT_TYPE);
		startActivityForResult(pickContactIntent, PICK_CONTACT_REQUEST);
	}

	private String getContactData(Uri contactUri) {
		Cursor cursor = null;
		StringBuilder response = null;

		String[] projection = new String[] { ContactsContract.Contacts._ID,
				ContactsContract.Contacts.DISPLAY_NAME, Phone.NUMBER };

		// Forma correcta, nuevo en API level 11, pero disponible con paquete de
		// compatibilidad
		/*
		 * CursorLoader cursorLoader = new CursorLoader(this, contactUri,
		 * projection, null, null, null); cursor =
		 * cursorLoader.loadInBackground();
		 */

		cursor = getContentResolver().query(contactUri, projection, null, null,
				null);
		startManagingCursor(cursor);

		if (cursor.moveToFirst()) {
			response = new StringBuilder();
			response.append("ID = "
					+ cursor.getString(cursor
							.getColumnIndex(ContactsContract.Contacts._ID)));
			response.append("\n");
			response.append("CONTACT NAME = "
					+ cursor.getString(cursor
							.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)));
			response.append("\n");
			response.append("PHONE = "
					+ cursor.getString(cursor.getColumnIndex(Phone.NUMBER)));
		}

		return response.toString();
	}

	/**
	 * Asynchrounos operation for query the contacts provider (database)
	 * 
	 * @author alquad
	 * 
	 */
	private class ContactDataAsyncTask extends AsyncTask<Uri, String, String> {

		@Override
		protected String doInBackground(Uri... params) {
			Uri contactUri = params[0];

			return getContactData(contactUri);
		}

		@Override
		protected void onPostExecute(String result) {
			txtvContact.setText(result);
			super.onPostExecute(result);
		}
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		Log.d("PickAContact", "onSaveInstanceState");

		if (outState == null)
			outState = new Bundle();

		outState.putString("txtvContent", txtvContact.getText().toString());

		super.onSaveInstanceState(outState);
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		Log.d("PickAContact", "onRestoreInstanceState()");
		String content = savedInstanceState.getString("txtvContent");

		if (content != null && !content.isEmpty()) {
			txtvContact.setText(content);
		}

		super.onRestoreInstanceState(savedInstanceState);
	}
}
